﻿var PressReleaseItemObejct = function (strID, Parent) {
    /*
        The individual PressRelease item that is displayed on the main page
        strID - [string] the ID of the container dom
        Parent - [object] the parent [PressReleasesObject] object
    */
    this.root;
    this.dom;

    /********************************************************************************
	These variables are commented out, because they need to be added using prototype.
	---------------------------------------------------------------------------------
	
	this.quickMessageHeight = 200;
	this.quickMessageDelay = 200;
	this.quickMessageMinimumDisplayWidth = 0; //the width, below with the quick message preview will not be shown
	this.strQuickMessageReadMoreText = "Read More";
	this.hasQuickMessage = true;
	this.useOthersGroupText = false; //a boolean variable showing if the types that belong to the others group should use their own name or the others group name. If set to TRUE uses the others group name.
	
	this.PopUp = {
		width : 560
		,height : 600
	};
	
	this.ButtonURIs = {
		pdf : './Content/Icons/default/pdf.gif'
		,xls : './Content/Icons/default/excel.gif'
		,doc : './Content/Icons/default/word.gif'
		,jpg : './Content/Icons/default/jpg.gif'
		,gif : './Content/Icons/default/gif.gif'
		,png : './Content/Icons/default/png.gif'
		,bmp : './Content/Icons/default/bmp.gif'
		,txt : './Content/Icons/default/txt.gif'
		,html : './Content/Icons/default/html.gif'
		,unknown : './Content/Icons/default/unknown.gif'
	};
	
	this.columnClassNamePrefex = "";
	this.useLocalAttachments = false;
	
	this.areAttachmentsFirst = false; //if TRUE the attachments will be part of the news column and displayed before any text
		
	********************************************************************************/

    var This = this
		, newsColumn = $('<div>')[0]
		, ChangeColumn = $('<div>')[0]
		, ComparisonChangeColumn = $('<div>')[0]
		, news = $('<div class="NewsColumn-Container PressRelease-NewsColumn">') //the news container
		, ComparisonChangeColumnContainer = $('<div class="ComparisonChangeColumn-Container ChangeColumn-Container PressRelease-Change">')[0]
		, ChangeColumnContainer = $('<div class="InstrumentChangeColumn-Container ChangeColumn-Container PressRelease-Change">')[0]
		, Attachments = $('<div class="PressRelease-Attachment">')
		, dateText = document.createTextNode(' ')
		, typeText = document.createTextNode(' ')
		, titleText = document.createTextNode(' ')
		, changeText = document.createTextNode(' ')
		, comparisonChangeText = document.createTextNode(' ')
		, changeTextContainer = $('<span>')[0]
		, comparisonChangeTextContainer = $('<span>')[0]
		, dateContainer = $('<span>')[0]
		, typeContainer = $('<span>')[0]
		, titleContainer = $('<a>')
		, Message = $('<div class="PressRelease-Message">')
		, MessageText = $('<div>')
		, MessageReadMore = $('<div class="PressRelease-ReadMore">')
		, MessageReadMoreHeight = 0
		, isMessageLoaded = false //shows if the news Item's message has already downloaded or not
		, isTouch = false //shows if the screen is a touch screen or not
		, hasTitleBeenTouched = false //shows if the title has been touched already or not i.e. if the quick message is showing or not
		, messageTimer = null
		, Data = null //[Object] a <PressReleaseItem> object gotten from the server that reprecents the current news item
		, Main = $('#Main')
		, AttachmentIcons = []
		, isVisible = false //shows if the item is visible or not
		, isTouchMove = false //used to stop the message closing when you scroll on the touch screen
    ;

    function _init() {
        if (typeof strID != 'string')
            strID = "";
        if (typeof hasTypes != 'boolean')
            hasTypes = true;

        if (typeof This.quickMessageHeight != 'number') {
            This.quickMessageHeight = 200;
        }
        if (typeof This.quickMessageDelay != 'number') {
            This.quickMessageDelay = 200;
        }

        if (typeof This.PopUp != 'object' || This.PopUp == null)
            This.PopUp = new Object();
        if (typeof This.PopUp.width != 'number')
            This.PopUp.width = 560;
        if (typeof This.PopUp.height != 'number')
            This.PopUp.height = 600;

        if (typeof This.hasQuickMessage != 'boolean')
            This.hasQuickMessage = true;
        if (typeof This.useOthersGroupText != 'boolean')
            This.useOthersGroupText = true;
        if (typeof This.quickMessageMinimumDisplayWidth != 'number') {
            This.quickMessageMinimumDisplayWidth = 0;
        }
        if (typeof This.strQuickMessageReadMoreText != 'string') {
            This.strQuickMessageReadMoreText = 'Read More';
        }
        if (typeof This.useLocalAttachments != 'boolean') {
            This.useLocalAttachments = false;
        }
        if (typeof This.columnClassNamePrefex != 'string') {
            This.columnClassNamePrefex = "";
        }
        if (typeof This.areAttachmentsFirst != 'boolean') {
            This.areAttachmentsFirst = false;
        }

        if (typeof This.ButtonURIs != 'object' || This.ButtonURIs == null) {
            This.ButtonURIs = {
                pdf: '/Content/Icons/default/pdf.gif'
				, xls: '/Content/Icons/default/excel.gif'
				, doc: '/Content/Icons/default/word.gif'
				, jpg: '/Content/Icons/default/jpg.gif'
				, gif: '/Content/Icons/default/gif.gif'
				, png: '/Content/Icons/default/png.gif'
				, bmp: '/Content/Icons/default/bmp.gif'
				, txt: '/Content/Icons/default/txt.gif'
                , mp4: '/Content/Icons/default/video.png'
				, unknown: '/Content/Icons/default/unknown.gif'
            };
        } else {
            if (typeof This.ButtonURIs.pdf != 'string') { This.ButtonURIs.pdf = '/Content/Icons/default/pdf.gif'; }
            if (typeof This.ButtonURIs.xls != 'string') { This.ButtonURIs.xls = '/Content/Icons/default/excel.gif'; }
            if (typeof This.ButtonURIs.doc != 'string') { This.ButtonURIs.doc = 'Content/Icons/default/word.gif'; }
            if (typeof This.ButtonURIs.jpg != 'string') { This.ButtonURIs.jpg = '/Content/Icons/default/jpg.gif'; }
            if (typeof This.ButtonURIs.gif != 'string') { This.ButtonURIs.gif = '/Content/Icons/default/gif.gif'; }
            if (typeof This.ButtonURIs.png != 'string') { This.ButtonURIs.png = '/Content/Icons/default/png.gif'; }
            if (typeof This.ButtonURIs.bmp != 'string') { This.ButtonURIs.bmp = '/Content/Icons/default/bmp.gif'; }
            if (typeof This.ButtonURIs.txt != 'string') { This.ButtonURIs.txt = '/Content/Icons/default/txt.gif'; }
            if (typeof This.ButtonURIs.mp4 != 'string') { This.ButtonURIs.mp4 = '/Content/Icons/default/video.png'; }
            if (typeof This.ButtonURIs.unknown != 'string') { This.ButtonURIs.unknown = '/Content/Icons/default/unknown.gif'; }
        }

        var dom = document.createElement('a');
        dom.onclick = openPopUp;
        dom.appendChild(document.createTextNode(This.strQuickMessageReadMoreText));
        dom.href = '#';
        MessageReadMore.append(dom);

        This.root = $(strID.length ? '<div id="' + strID + '">' : '<div>');
        This.root.addClass('PressRelease');
        This.dom = This.root[0];

        dateContainer.appendChild(dateText);
        typeContainer.appendChild(typeText);
        titleContainer.append(titleText);
        changeTextContainer.appendChild(changeText);
        comparisonChangeTextContainer.appendChild(comparisonChangeText);

        dateContainer.className = 'PressRelease-NewsDate';
        typeContainer.className = 'PressRelease-NewsType';
        titleContainer[0].className = 'PressRelease-NewsTitle';

        newsColumn.className = 'NewsColumn  ColumnLayoutColumn';
        ChangeColumn.className = 'InstrumentChangeColumn  ColumnLayoutColumn  Change-Column';
        ComparisonChangeColumn.className = 'ComparisonChangeColumn  ColumnLayoutColumn  Change-Column';

        switch (Parent.layout) {
            case 4:
                newsColumn.className = This.columnClassNamePrefex + newsColumn.className;
                ChangeColumn.className = 'CombinedChangeColumn  ColumnLayoutColumn  Change-Column';
                break;
            case 3:
                break;
            case 2:
            case 1:
                newsColumn.className = This.columnClassNamePrefex + newsColumn.className;
                ChangeColumn.className = This.columnClassNamePrefex + ChangeColumn.className;
                ComparisonChangeColumn.className = This.columnClassNamePrefex + ComparisonChangeColumn.className;
                break;
            case 0:
                newsColumn.className = This.columnClassNamePrefex + newsColumn.className;
                break;
        }

        if (This.areAttachmentsFirst) {
            news.append(Attachments);
        }
        news.append(dateContainer);
        news.append(document.createTextNode(' '));
        if (Parent.hasTypes)
            news.append(typeContainer);
        news.append($('<br>')[0]);
        news.append(titleContainer);

        if (This.areAttachmentsFirst) {
            news.append($('<div class="PressRelease-AttachmentClearer">'));
        }

        newsColumn.appendChild(news[0]);

        This.dom.appendChild(newsColumn);

        switch (Parent.layout) {
            case 3: //Both Change and Comparison in separate columns
            case 1: //Change in a single column
                ChangeColumn.appendChild(ChangeColumnContainer);
                ChangeColumnContainer.appendChild(changeTextContainer);
                This.dom.appendChild(ChangeColumn);
                if (Parent.layout == 1) {
                    break;
                }
            case 2: //comparison in a single column
                ComparisonChangeColumn.appendChild(ComparisonChangeColumnContainer);
                ComparisonChangeColumnContainer.appendChild(comparisonChangeTextContainer);
                This.dom.appendChild(ComparisonChangeColumn);
                break;
            case 4: //both Change and Comparison in a single columns
                ChangeColumn.appendChild(ChangeColumnContainer);
                ChangeColumnContainer.appendChild(changeTextContainer);
                ChangeColumnContainer.appendChild(document.createTextNode(' / '));
                ChangeColumnContainer.appendChild(comparisonChangeTextContainer);
                This.dom.appendChild(ChangeColumn);
                break;
        }

        if (!This.areAttachmentsFirst) {
            This.root.append(Attachments);
        }
        This.root.append(Message);

        Message.css({
            overflow: 'hidden'
			, wordSpacing: 0
			, height: 0
        });

        if (typeof This.dom.ontouchstart == 'object') {
            isTouch = true;
        }
        if (This.hasQuickMessage) {

            Message.append(MessageText);
            Message.append(MessageReadMore);

            if (isTouch) {

                $(document).on('touchmove', function () {
                    isTouchMove = true;
                });


                $(document).on('touchend', function () {
                    if (isTouchMove) {
                        isTouchMove = false;
                    } else {
                        hideMessage();
                    }
                });


                This.root.on('touchend', function (e) {
                    /*
                        Stops the bubbling so that when the user click on the press release the quick message will not close
                    */
                    if (!isTouchMove) {
                        e.stopPropagation();
                    }
                });
            } else {
                This.root.mouseleave(hideMessage);
                titleContainer.mouseenter(openQuickMessage);
                titleContainer.mouseleave(clearMessageTimer);
            }
        }

        if (isTouch) {

            titleContainer.on('touchend', function (e) {

                if (e.originalEvent.touches.length > 1 || isTouchMove) {
                    return;
                }

                if (hasTitleBeenTouched || !This.hasQuickMessage) {
                    openPopUp();
                } else {
                    showMessage();
                }
                hasTitleBeenTouched = !hasTitleBeenTouched;
            });

        } else {
            titleContainer[0].href = '#';
            titleContainer[0].onclick = openPopUp;
        }
    };

    function openQuickMessage() {
        if (isMessageLoaded && This.quickMessageDelay > 0) {
            messageTimer = setTimeout(function () {
                showMessage();
            }, This.quickMessageDelay);
        } else {
            showMessage();
        }
    }
    this.closeQuickMessage = hideMessage;

    this.load = function () {
        if (This.hasQuickMessage) {
            Message.css({ height: 'auto' });

            MessageReadMoreHeight = MessageReadMore.height();

            Message.css({ height: 0 });

            MessageText.css({
                height: This.quickMessageHeight
				, overflow: 'hidden'
            });
        }
        this.remove();
    };

    function showMessage() {
        if (Data == null || !isVisible || This.quickMessageMinimumDisplayWidth && Main.width() < This.quickMessageMinimumDisplayWidth)
            return;

        Parent.closeAllMessages();
        Data.ID = Data.Id;
        var height = This.quickMessageHeight + MessageReadMoreHeight;

        if (isMessageLoaded) {
            Utility.Effects.show(null, Message, height);
        } else {
            Utility.Effects.hide(null, Message, function () {
                MessageText.empty();
                MessageText.load(
					  Utility.baseURI + 'Home/Message/?id=' + Data.Id
					  , function (text, strStatus, request) {
					      Utility.Effects.show(null, Message, height);
					      //checks to see if the message could be retrived, if not, then then does not mark the message as loaded
					      switch (strStatus) {
					          case 'success':
					          case 'notmodified':
					              isMessageLoaded = true;
					              break;
					      }
					  }
				);
            });
        }
    }
    function clearMessageTimer() {
        if (typeof messageTimer == 'number') {
            clearTimeout(messageTimer);
        }
    }
    function hideMessage() {
        hasTitleBeenTouched = false;
        clearMessageTimer();
        Utility.Effects.hide(null, Message);
    }
    function openPopUp() {
        if (!isVisible) {
            return;
        }
        Utility.blur();

        //alert('width=' + This.PopUp.width + ',height=' + This.PopUp.height + ',menubar=0,toolbar=0,location=0,scrollbars=1,resizable=1,fullscreen=0');
        //window.open(Utility.baseURI + 'GetPressRelease/?ID=' + Data.ID + '&lang=' + Parent.culture + '&companycode=' + Parent.companyCode + '&v=' + Parent.queryVersion, '_blank', 'width=' + This.PopUp.width + ',height=' + This.PopUp.height + ',menubar=0,toolbar=0,location=0,scrollbars=1,resizable=1');
        window.location = Utility.baseURI + 'Home/News/?id=' + Data.Id;
    }    

    this.set = function (news, clearOldNews, AttachmentsArr) {
        /*
            Sets the new news item to the Press release
            news - [Object] a <PressReleaseItem> object gotten from the server
            clearOldNews - [Boolean] if set to true, the old news Item will completely dissepear, while if set to false the old one will simply fade out
            AttachmentsArr - [array] an array containing <PressReleaseItemAttachment> objects gotten from the server
        */
        var newHeight, oldHeight = clearOldNews ? 0 : This.root.height();

        Data = news;
        removeMessage();
        isVisible = true;

        Data.type = '';// Parent.Types.getCustomName(Data.type, Data.SourceID, Data.TypeID, this.useOthersGroupText); //Sets type name to be the correct type name, based on the custom names and others group

        This.root.css({ visibility: 'visible' });

        this.root.stop(true, false).show().animate({
            height: oldHeight + 'px',
            opacity: 0
        }, null, null, function () {

            setNews(AttachmentsArr);

            This.root.css({
                position: 'absolute'
				, top: '0px'
				, left: '0px'
				, height: 'auto'
				, width: This.root.width() + 'px'
				, opacity: 0.01
            });

            newHeight = This.root.height();

            This.root.css({
                position: 'static'
				, top: 'auto'
				, left: 'auto'
				, height: oldHeight + 'px'
				, width: 'auto'
				, opacity: 0
            }).animate({
                opacity: 1,
                height: newHeight + 'px'
            }, 'slow', null, function () {
                This.root.css({ height: 'auto' });
                ToolContainer.checkHeight(This.hasQuickMessage ? This.quickMessageHeight : 0);
            });

        });
    };

    function removeMessage() {
        isMessageLoaded = false;
        Utility.Effects.hide(null, Message, function () {
            MessageText.empty();
        });
    }
    this.hide = function () {
        isVisible = false;
        this.root.stop(true).animate({
            opacity: 0
        }, null, null, function () {
            This.root.css({ visibility: 'hidden' });
        });
    };
    this.remove = function (isImidate) {
        if (typeof isImidate != 'boolean') {
            isImidate = false;
        }

        Data = null;
        isVisible = false;
        //titleContainer[0].onclick = null;

        if (typeof messageTimer == 'number') {
            clearTimeout(messageTimer);
        }

        this.root.stop(true).animate({
            opacity: 0,
            height: '0px'
        }, isImidate ? 0 : null, null, function () {
            This.root.hide();
        });
    };

    function setNews(AttachmentsArr) {
        /*
            Set a news item as the news of this Object
            AttachmentsArr - [array] an array containing <PressReleaseItemAttachment> objects gotten from the server
        */
        var index, obj, icon;

        dateContainer.removeChild(dateText);
        typeContainer.removeChild(typeText);
        titleContainer[0].removeChild(titleText);

        changeTextContainer.className = '';
        changeTextContainer.removeChild(changeText);
        changeText = document.createTextNode(Data.strChange);
        changeTextContainer.appendChild(changeText);

        if (Data.change > 0) {
            changeTextContainer.className = 'Change-Positive';
        } else if (Data.change < 0) {
            changeTextContainer.className = 'Change-Negative';
        } else {
            changeTextContainer.className = 'Change-Neutral';
        }

        comparisonChangeTextContainer.className = '';
        comparisonChangeTextContainer.removeChild(comparisonChangeText);
        comparisonChangeText = document.createTextNode(Data.strComparisonChange);
        comparisonChangeTextContainer.appendChild(comparisonChangeText);

        if (Data.comparisonChange > 0) {
            comparisonChangeTextContainer.className = 'Change-Positive';
        } else if (Data.comparisonChange < 0) {
            comparisonChangeTextContainer.className = 'Change-Negative';
        } else {
            comparisonChangeTextContainer.className = 'Change-Neutral';
        }
        Data.title = Data.Title;
        titleText = document.createTextNode(Data.title);
        var dateFormated = $.format.date(Data.DateTime.toDate(), Settings.dateFormat);
        Data.formatedDate = dateFormated;
        dateText = document.createTextNode(Data.formatedDate);

        dateContainer.appendChild(dateText);
        titleContainer[0].appendChild(titleText);

        typeText = document.createTextNode(Data.type);
        typeContainer.appendChild(typeText);

        //Adds the Attachments
        Attachments.empty();
        AttachmentIcons = [];
        Data.hasAttachments = Data.Attachment;
        if (!Data.hasAttachments) {
            Attachments.css({
                display: 'none'
            });
            return;
        }
        Attachments.css({
            display: 'block'
        });

        index = AttachmentsArr.length;
        while (index--) {
            obj = AttachmentsArr[index];
            Data.ID = Data.Id;
            obj.prID = obj.PressreleaseId;
            obj.filename = obj.FileName;
            obj.atID = obj.Id;
            obj.mime = obj.MimeType;

            if (obj.prID == Data.ID) {

                icon = new ButtonObject({ title: obj.filename });
                Attachments.append(icon.dom);

                if (This.useLocalAttachments) {
                    loadAttachmentButton(icon, obj.filename, Utility.baseURI + './Attachments.ashx?id=' + obj.atID, obj.mime);
                } else {
                    loadAttachmentButton(icon, obj.filename, Parent.strAttachmentLocationURL + './' + obj.atID + '/' + obj.filename, obj.mime);
                }

                AttachmentIcons.push(icon);
            }
        }
    }
    function loadAttachmentButton(obj, fileName, clickUrl, mime) {
        var url = fileName.match(/\..*?$/g) //gets the file extention
        ;

        obj.onClickCall = function () {
            window.open(clickUrl, '_blank');
        }

        //gets the url of the icon
        if (url == null) {
            //if the file name is one of those nice ones where the DB logic is broken, then the mime type if checked instead

            url = '?'; //the default value of the mime can't be identified
            mime = mime.toLowerCase();
            if (mime.match(/\/pdf$/g) != null && mime.match(/\/pdf$/g).length) {
                url = '.pdf';
            } else if (mime.match(/excel$/g) != null && mime.match(/excel$/g).length) {
                url = '.xls';
            } else if (mime.match(/word$/g) != null && mime.match(/word$/g).length) {
                url = '.doc';
            } else {
                switch (mime) {
                    case 'image/jpeg':
                    case 'image/pjpeg':
                        url = '.jpg';
                        break;
                    case 'image/gif':
                        url = '.gif';
                        break;
                    case 'image/png':
                        url = '.png';
                        break;
                    case 'image/bmp':
                        url = '.bmp';
                        break;
                    case 'text/plain':
                        url = '.txt';
                        break;
                    case 'text/html':
                        url = '.html';
                        break;
                    case 'video/mp4':
                        url = '.mp4';
                        break;
                    case 'application/xml':
                    case 'text/xml':
                        url = '.xml';
                        break;

                }
            }
        } else {
            url = url.length ? url[0].toLowerCase() : '?';
        }

        switch (url) {
            case '.pdf':
                url = This.ButtonURIs.pdf;
                break;
            case '.xlsx':
            case '.xls':
                url = This.ButtonURIs.xls;
                break;
            case '.docx':
            case '.doc':
                url = This.ButtonURIs.doc;
                break;
            case '.jpg':
            case '.jpge':
                url = This.ButtonURIs.jpg;
                break;
            case '.gif':
                url = This.ButtonURIs.gif;
                break;
            case '.png':
                url = This.ButtonURIs.png;
                break;
            case '.bmp':
                url = This.ButtonURIs.bmp;
                break;
            case '.txt':
                url = This.ButtonURIs.txt;
                break;
            case '.html':
            case '.htm':
                url = This.ButtonURIs.html;
                break;
            case '.rtf':
                url = This.ButtonURIs.rtf;
                break;
            case '.xml':
                url = This.ButtonURIs.xml;
                break;
            case '.mp4':
                url = This.ButtonURIs.mp4;
                break;
            default:
                url = This.ButtonURIs.unknown;
                break;
        }

        obj.load(url);
    }
    _init();
};